package fun.chutianshu.springsecurity_04.security;

import fun.chutianshu.springsecurity_04.entity.SysPermission;
import fun.chutianshu.springsecurity_04.entity.SysUser;
import fun.chutianshu.springsecurity_04.service.SysPermissionService;
import fun.chutianshu.springsecurity_04.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
//实现了 spring security 中的用户信息服务类
//覆盖了接口中用来读取指定用户名用户信息的方法 loadUserByUsername
public class JwtUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private PasswordEncoder bcryptEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = userService.findByUserName(username);

        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        List<SysPermission> sysPermissions = sysPermissionService.findByAdminUserId(user.getId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for(SysPermission sysPermission:sysPermissions){
            if(sysPermission!=null && sysPermission.getName()!=null&& sysPermission.getUrl()!=null){
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getName());
                //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                grantedAuthorities.add(grantedAuthority);
            }
        }
        return new User(user.getUsername(), user.getPassword(),
                grantedAuthorities);
    }

    public SysUser save(String username,String password) {
        SysUser newUser = new SysUser();
        newUser.setUsername(username);
        newUser.setPassword(bcryptEncoder.encode(password));
        return userService.insert(newUser);
    }

}